package com.slink.fxfk.framework.util;

import java.io.StringWriter;
import java.text.SimpleDateFormat;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

/**
 * json工具类
 */
public class JSONUtils {
	private static final ObjectMapper mapper = new ObjectMapper();
	private static final SimpleDateFormat formatter = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	static {
		mapper.setDateFormat(formatter);
		mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
	}

	/**
	 * 将对象转成JSON格式字符串返回
	 * 
	 */
	public static String toJson(Object object) {
		StringWriter writer = new StringWriter();
		try {
			mapper.writeValue(writer, object);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writer.toString();
	}

	/**
	 * 将json字符串转成指定类型的对象
	 * 
	 */
	public static <T> T readJson(String json, Class<T> cls) {
		if (json == null)
			return null;
		try {
			return mapper.readValue(json, cls);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
